from datetime import datetime

from flask import session, current_app
from app.models import Log
from . import db


class Logging:
    def __init__(self, request, op=None):
        self.option = op
        self.ip = request.remote_addr
        self.user = session.get("username")
        self.page = request.path

    # 警告log文件
    def warn_log(self):
        log_model = Log(ip=self.ip, user=self.user, page=self.page, option=self.option)
        db.session.add(log_model)
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()

    # 一般log文件
    def info_log(self):
        with open("log.txt", 'a+', encoding='utf-8') as file:
            file.write("ip：{}  user：{}  page：{}  option：{}  create_time：{}\n".format(self.ip,self.user,self.page,self.option,datetime.now()))

    # 错误log文件
    def error_log(self):
        pass

